﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace VirusTotalAPI
{
    class parse_jsontxt
    {
        string notscaned, Scanned, NotScanned;
        string bs = "BeenScanned";
        string ns = "NotScanned";
        int start = 0;
        List<string> ListScanedResponse = new List<string>();
        List<string> NotListScanedResponse = new List<string>();
        RootObjects testing = new RootObjects();
        Hashtable returned = new Hashtable();
        public void tobeparsed(String tobe)
        {
            string part1, part2;
            //Console.WriteLine(tobe.Contains("{\"response_code\": 0"));
            if (tobe.Contains("{\"response_code\": 0"))
            {
                //Console.WriteLine("at least one file has not been proccessed");
                //Console.WriteLine(tobe.IndexOf("{\"response_code\": 0"));

                do
                {
                    part1 = tobe.Substring(0, tobe.IndexOf("{\"response_code\": 0"));
                    part2 = tobe.Substring(tobe.IndexOf("{\"response_code\": 0"), ((tobe.Length) - (tobe.IndexOf("{\"response_code\": 0"))));
                    //Console.WriteLine(part2.IndexOf("{\"response_code\": 0"));
                    if (start > 0)
                    {
                        notscaned += part2.Substring(part2.IndexOf("{\"response_code\": 0"), 160);
                    }
                    else
                    {
                        notscaned = part2.Substring(part2.IndexOf("{\"response_code\": 0"), part2.IndexOf("{\"scans\":"));
                    }

                    int yousuck = part2.IndexOf("{\"scans\":");
                    if (yousuck > 2)
                    {
                        tobe = part1 + part2.Substring(part2.IndexOf("{\"scans\":"), ((part2.Length) - (part2.IndexOf("{\"scans\":"))));
                    }
                    else
                    {
                        tobe = part1.Substring(0, ((part1.Length) - 2)) + part2.Substring(160, ((part2.Length) - 160));
                    }
                    ++start;

                } while (tobe.Contains("{\"response_code\": 0"));


            }
            this.returned.Add("BeenScanned", tobe);
            this.returned.Add("NotScanned", notscaned);

        }
        public void Scaned()
        {
            string A, B, C;
            List<string> te = new List<string>();

            while (Scanned.Contains("{\"scans\": {"))
            {

                int chop = 0;
                chop = Scanned.IndexOf("}, {\"scans\": {");
                if (chop > 0)
                {
                    A = Scanned.Substring(1, chop);
                    B = Scanned.Substring(Scanned.IndexOf("}, {\"scans\": {"), ((Scanned.Length) - (Scanned.IndexOf("}, {\"scans\": {"))));
                    C = B.Substring(3, ((B.Length) - (B.IndexOf("{\"scans\": {"))));
                }
                else
                {
                    A = Scanned.Substring(1, Scanned.LastIndexOf("}]"));
                    B = Scanned.Substring((Scanned.LastIndexOf("}]")), ((Scanned.Length) - (Scanned.LastIndexOf("}]"))));
                    C = B;

                }

                te.Add(A);
                Scanned = "[" + C + "]";
            }

            this.ListScanedResponse = te;
            this.Scanned = "";
        }
        public void NotScaned()
        {
            string part1;
            string[] NotScanedparts;
            Hashtable menoscan = new Hashtable();
            List<string> temp = new List<string>();
            while (NotScanned.Contains("{\"response_code"))
            {
                NotScanned = NotScanned.Replace("}, {\"response_code\"", "}~ {\"response_code\"");
                NotScanned = NotScanned.Replace("{", "");
                NotScanned = NotScanned.Replace("}", "");
                NotScanned = NotScanned.Replace("\"", "");
                NotScanedparts = NotScanned.Split('~');
                foreach (string parts in NotScanedparts)
                {
                    part1 = parts.Trim();
                    temp.Add(part1);

                }
            }
            this.NotListScanedResponse = temp;
            this.notscaned = "";
        }
        public bool hashkeyScanned(string Key_value)
        {

            if (string.Equals(Key_value, this.bs, StringComparison.OrdinalIgnoreCase))
            {

                if (this.returned.ContainsKey("BeenScanned"))
                {
                    this.Scanned = this.returned["BeenScanned"].ToString();
                    Console.WriteLine("Start Scanned list  creation");
                }

                return true;
            }
            else
            {
                return false;
            }

        }
        public bool HashKeyNotScanned(string Key_value)
        {

            if (string.Equals(Key_value, this.ns, StringComparison.OrdinalIgnoreCase))
            {
                if (this.returned.ContainsKey("NotScanned"))
                {
                    this.NotScanned = this.returned["NotScanned"].ToString();
                    Console.WriteLine("Start Not Scanned listcreation");
                }
                return true;
            }
            else
            {
                return false;
            }


        }
        public void buildrootscannedobject()
        {

            string A, scantobe;
            foreach (string scanned in this.ListScanedResponse)
            {
                Scans igotscaned = new Scans();
                Hashtable tobeused = new Hashtable();
                scantobe = scanned.Substring(0, scanned.IndexOf("\"scan_id\":"));
                A = scanned.Substring(scantobe.Length, ((scanned.Length) - (scanned.IndexOf("\"scan_id\":"))));
                A = A.TrimEnd('}');
                A = A.Replace("Scan finished, scan information embedded in this object", "Scan finished scan information embedded in this object");
                scantobe = scantobe.Replace("{\"scans\": {", "");
                scantobe = scantobe.Replace("}},", "},");
                scantobe = scantobe.Replace("},", "}~");
                scantobe = scantobe.Substring(0, ((scantobe.Length) - 2));
                string[] scnay = scantobe.Split('~');
                string[] yech = A.Split(',');

                foreach (string pair in yech)
                {
                    if (pair.Length > 0)
                    {
                        string[] parseplease = pair.Split(':');
                        List<String> list = new List<String>();
                        string key, val;
                        foreach (string a in parseplease)
                        {

                            list.Add(a);

                        }
                        if (list.Count > 2)
                        {
                            key = list[0];
                            key = key.Replace("\"", "");
                            key = key.Trim();
                            val = (list[1] + ":" + list[2]);
                            val = val.Replace("\"", "");
                            val = val.Trim();
                        }
                        else
                        {
                            key = list[0];
                            key = key.Replace("\"", "");
                            key = key.Trim();
                            val = list[1];
                            val = val.Replace("\"", "");
                            val = val.Trim();
                        }
                        tobeused.Add(key, val);
                    }

                }

                foreach (string iamascan in scnay)
                {
                    string p, dumb;
                    string[] first, second, third;

                    //Console.WriteLine(iamascan.ToString());
                    first = iamascan.Split('{');
                    p = first[0];
                    p = p.Replace(":", "");
                    p = p.Replace("\"", "");
                    p = p.Trim();
                    dumb = first[1];
                    dumb = dumb.Replace("}", "");
                    second = dumb.Split(',');
                    Hashtable thecrab = new Hashtable();
                    foreach (string boo in second)
                    {
                        third = boo.Split(':');
                        string get = third[0];
                        string set = third[1];
                        get = get.Replace("\"", "");
                        get = get.Trim();
                        set = set.Replace("\"", "");
                        set = set.Trim();
                        thecrab.Add(get, set);

                    }
                    igotscaned.Add(p.ToString(), new Scan(thecrab["result"].ToString(), Convert.ToBoolean(thecrab["detected"].ToString()), thecrab["version"].ToString(), thecrab["result"].ToString(), thecrab["update"].ToString()));

                }
                //public RootObject(Scans scan,string scan_id, string sha1, string resource, int rc, string sd, string link, string vm, int totals, int positive, string s256, string m5)
                if (tobeused.Count > 0)
                {
                    this.testing.Add(tobeused["resource"].ToString(), new RootObject(igotscaned, tobeused["scan_id"].ToString(), tobeused["sha1"].ToString(), tobeused["resource"].ToString(),
                    Convert.ToInt32(tobeused["response_code"].ToString()), tobeused["scan_date"].ToString(), tobeused["permalink"].ToString(),
                    tobeused["verbose_msg"].ToString(), Convert.ToInt32(tobeused["total"].ToString()), Convert.ToInt32(tobeused["positives"].ToString()), tobeused["sha256"].ToString(), tobeused["md5"].ToString()));
                }
            }
            this.ListScanedResponse.Clear();
        }
        public void buildrootnotscannedobject()
        {
            string[] peices;
            Hashtable notscannedhash = new Hashtable();
            foreach (string notscanned in this.NotListScanedResponse)
            {
                string part = notscanned.Replace("The requested resource is not among the finished, queued or pending scans", "The requested resource is not among the finished queued or pending scans");
                peices = part.Split(',');
                string[] minipeices;

                foreach (string pairs in peices)
                {

                    minipeices = pairs.Split(':');
                    string key = minipeices[0].ToString();
                    key = key.Trim();
                    string value = minipeices[1].ToString();
                    value = value.Trim();
                    notscannedhash.Add(key, value);

                }
                if (notscannedhash.Count > 0)
                {
                    //public RootObject(string resource, int rc, string vm)

                    this.testing.Add(notscannedhash["resource"].ToString(), new RootObject(notscannedhash["resource"].ToString(), Convert.ToInt32(notscannedhash["response_code"].ToString()), notscannedhash["verbose_msg"].ToString()));

                }
                notscannedhash.Clear();
            }
            this.NotListScanedResponse.Clear();

        }
        public void createjsontxt()
        {
            Console.WriteLine("Create Text file with JSON response from VirusTotal");
            System.IO.StreamWriter Json_out = new System.IO.StreamWriter("\\json.txt");
            foreach (RootObject test in this.testing)
            {

                Json_out.WriteLine();
            }
            Json_out.WriteLine("");
            Json_out.Close();
        }
        public void bulidworddoc(Hashtable filenamestomd5, string outputfilepath)
        {
                Program.AutomateWord(this.testing, filenamestomd5, outputfilepath);        
        }
    }

    public class RootObject
    {
        public Scans scans { get; set; }
        public string scan_id { get; set; }
        public string sha1 { get; set; }
        public string resource { get; set; }
        public int response_code { get; set; }
        public string scan_date { get; set; }
        public string permalink { get; set; }
        public string verbose_msg { get; set; }
        public int total { get; set; }
        public int positives { get; set; }
        public string sha256 { get; set; }
        public string md5 { get; set; }

        public RootObject(Scans scan, string scan_id, string sha1, string resource, int rc, string sd, string link, string vm, int totals, int positive, string s256, string m5)
        {
            this.scans = scan;
            this.scan_id = scan_id;
            this.sha1 = sha1;
            this.resource = resource;
            this.response_code = rc;
            this.scan_date = sd;
            this.permalink = link;
            this.verbose_msg = vm;
            this.total = totals;
            this.positives = positive;
            this.sha256 = s256;
            this.md5 = m5;
        }
        public RootObject(string resource, int rc, string vm)
        {
            this.resource = resource;
            this.response_code = rc;
            this.verbose_msg = vm;
        }
    }
    public class RootObjects : DictionaryBase
    {
        public void Add(string key, RootObject newScans)
        {
            Dictionary.Add(key, newScans);
        }
        public void Remove(string key)
        {
            Dictionary.Remove(key);
        }
        public RootObject this[string key]
        {
            get { return (RootObject)Dictionary[key]; }
            set { Dictionary[key] = value; }
        }
        public ICollection Keys
        {
            get
            {
                return (Dictionary.Keys);
            }
        }
    }
    public class Scan
    {
        public string Provider { get; set; }
        public bool Detected { get; set; }
        public string Version { get; set; }
        public string Result { get; set; }
        public string Update { get; set; }

        public Scan(string p, bool d, string v, string r, string u)
        {
            this.Provider = p;
            this.Detected = d;
            this.Version = v;
            this.Result = r;
            this.Update = u;
        }
    }
    public class Scans : DictionaryBase
    {
        public void Add(string key, Scan newScans)
        {
            Dictionary.Add(key, newScans);
        }
        public void Remove(string key)
        {
            Dictionary.Remove(key);
        }
        public Scan this[string key]
        {
            get { return (Scan)Dictionary[key]; }
            set { Dictionary[key] = value; }
        }
        public ICollection Keys
        {
            get
            {
                return (Dictionary.Keys);
            }
        }
    }

}
